package comu.hnevc.zh.testdemo.dao;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;


public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
    private static DatabaseHelper instance;
    private Map<String,Dao> daos=new HashMap<>();
    public static synchronized DatabaseHelper getInstance(Context context){
        if (instance==null){
            synchronized (DatabaseHelper.class){
                if(instance==null){
                    instance=new DatabaseHelper(context);
                }
            }
        }
        return  instance;
    }
    private DatabaseHelper(Context context) {
        super(context, "mydb.db", null, 1);
    }
    public  synchronized Dao getDao(Class clazz) throws SQLException {
        Dao dao=null;
        String className=clazz.getSimpleName();
        if (daos.containsKey(className)){
         dao=daos.get(className);
        }
        if (dao==null){
            dao=super.getDao(clazz);
            daos.put(className,dao);
        }
        return dao;
    }


    @Override
    //创建数据库调用的方法
    public void onCreate(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource) {
        try {
            TableUtils.createTable(connectionSource,RechargeBean.class);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource, int i, int i1) {
        try {
            TableUtils.dropTable(connectionSource,RechargeBean.class,true);
            onCreate(sqLiteDatabase,connectionSource);
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }


    //释放资源
    @Override
    public void close() {
        super.close();
        for (String  key : daos.keySet()){
            Dao dao=daos.get(key);
            dao=null;
        }
    }
}
